package domain

import (
	"database/sql"
	"time"

	"gitee.com/waterwx_admin/banking/errs"
	"gitee.com/waterwx_admin/banking/logger"
	_ "github.com/go-sql-driver/mysql"
)

// ********数据库适配器********

// 结构体
type CustomerRepositoryDb struct {
	client *sql.DB
}

// 查询所有的方法 // 定义结构体的方法，实现CustomerRepository接口
func (d CustomerRepositoryDb) FindAll(status string) ([]Customer, *errs.AppError) {

	var rows *sql.Rows
	var err error


	if status == "1" {	// 激活状态
		findAllSql := "select customer_id, name, city, zipcode, date_of_birth, status from customers where status = ?"
		rows, err = d.client.Query(findAllSql,status)
	} else if status == "0" {	// 未激活状态
		findAllSql := "select customer_id, name, city, zipcode, date_of_birth, status from customers where status = ?"
		rows, err = d.client.Query(findAllSql,status)
	}else {	// 没有区分是否激活
		findAllSql := "select customer_id, name, city, zipcode, date_of_birth, status from customers "	
		rows, err = d.client.Query(findAllSql)
	}

	if err != nil {
		logger.Error("Error while querying customers table " + err.Error())
		return nil, errs.NewUnexceptedError("Unexcepted database error ----> 数据库错误问题")
	}
	customers := make([]Customer, 0)
	for rows.Next() {
		var c Customer
		rows.Scan(&c.Id, &c.Name, &c.City, &c.Zipcode, &c.DateofBirth, &c.Status)
		if err != nil {
			logger.Error("Error while scanning customers table " + err.Error())
			return nil, errs.NewUnexceptedError("Unexcepted database error ----> 数据库错误问题")
		}
		customers = append(customers, c)
	}
	return customers, nil
}

// 根据Id查询客户 // 定义结构体的方法，实现CustomerRepository接口
func (d CustomerRepositoryDb) ById(id string) (*Customer, *errs.AppError) {
	customerSql := "select customer_id, name, city, zipcode, date_of_birth, status  from customers where customer_id = ?"

	row := d.client.QueryRow(customerSql, id)
	
	var c Customer
	err := row.Scan(&c.Id, &c.Name, &c.City, &c.Zipcode, &c.DateofBirth, &c.Status)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, errs.NewNotFoundError("Customer not found")
		} else {
			logger.Error("Error while scanning customer " + err.Error())
		return nil, errs.NewUnexceptedError("Unexcepted database error ----> 数据库错误问题")
		}
	}
	return &c, nil

}

// 构造函数
func NewCustomerRepositoryDb() CustomerRepositoryDb {
	client, err := sql.Open("mysql", "root:Paso2021@ipaso.cn@tcp(172.16.20.149:3306)/banking")
	if err != nil {
		panic(err)
	}
	// See "Important settings" section.
	client.SetConnMaxLifetime(time.Minute * 3)
	client.SetMaxOpenConns(10)
	client.SetMaxIdleConns(10)
	return CustomerRepositoryDb{client}
}
